import "./register.scss";
import $ from "jquery";
import {cookie} from "../../libs/common.js";
import Cart from "../../parts/cart/cart";
import ProfileMgr from "../../data/ProfileMgr";

;;(function(){
    let STATE       = {
        HIDDEN      : 0,
        NORMAL      : 1,
        SUCCESS     : 2,
        ERROR       : 3,
    }
    let regList = {
        "usrErr": /[^a-z\u2E80-\u9FFF\-_0-9]/i,
        "usrReg" :  /^[a-z\u2E80-\u9FFF\-_0-9]{4,20}$/i,
        "pureNumber":/^\d+$/i,
        "maxlength4" : /^.{0,3}$/,
        "hasNumber" : /\d/,
        "hasLetter" : /[a-zA-Z]/,
        "pwdErr": /[^a-z0-9\u2E80-\u9FFF]/i,
        "minlength6" : /^.{0,5}$/,
        "mailReg": /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@[0-9a-z]{2,9}\.[a-z]{2,6}(\.[a-z]{2,3})?$/i,
    } 
    // 该变量表示是否已经发送了请求;
    let loading = false;

    function validate(str,reg){
        return reg.test(str);
    }
    function changeTipTxt(iptEle,state,text){
        let html = ``;
        switch(state){
            case STATE.HIDDEN:
                iptEle.removeClass("error");
            break;
            case STATE.NORMAL:
                iptEle.removeClass("error");
                html += `<span class="tips_nor">
                    ${text}
                </span>`;
            break;
            case STATE.SUCCESS:
                iptEle.removeClass("error");
                html += `<span class="tips_right">
                    <b class="icon icon_msg0 icon_msg0_right">&nbsp;</b>
                </span>`;
            break;
            case STATE.ERROR: 
                iptEle.addClass("error");
                html += `<span class="tips_error">
                    <b class="icon icon_msg0 icon_msg0_warn">&nbsp;</b>
                    <span class="warn">${text}</span>
                </span>`;
            break;
        }
        iptEle.next().html(html);
    }
    // 用户名验证
    function validateUser(e){
        let value = $(this).val();

        if(e.type == "focus"){
            if(value.length <= 0){
                changeTipTxt($(this),STATE.NORMAL, "支持中文,英文,数字,字母,-,_ 的4~20位字符");
                return false;
            }
        }
        if(validate(value, regList.usrErr)){
            changeTipTxt($(this), STATE.ERROR, "格式错误");
            return false;
        }
        else{
            if(e.type == "blur"){
                if(value.length <= 0){
                    changeTipTxt($(this), STATE.HIDDEN, "");
                    return false;
                }
                if(validate(value,regList.maxlength4)){
                    changeTipTxt($(this), STATE.ERROR, "长度只能在4-20字符之间");
                    return false;
                }
                if(validate(value,regList.pureNumber)){
                    changeTipTxt($(this), STATE.ERROR, "用户名不能为纯数字");
                    return false;
                }
            
                if(validate(value,regList.usrReg)){
                    changeTipTxt($(this), STATE.SUCCESS, "");
                    return true;
                }
            }
            changeTipTxt($(this), STATE.NORMAL, "支持中文,英文,数字,字母,-,_ 的4~20位字符");
            return false;
        }
    }
    // 密码验证
    function validatePass(e){
        let value = $(this).val(),
            strength = 0;
        if(e.type == "focus"){
            if(value.length <= 0){
                changeTipTxt($(this), STATE.NORMAL, "使用字母,数字,符号两种及以上组合,6-20个字符");
                return false;
            }
        }
        if(e.type == "blur"){
            if(value.length <= 0){
                changeTipTxt($(this), STATE.HIDDEN, "");
                return false;
            }
        }
        if(value.length <= 0){
            changeTipTxt($(this), STATE.NORMAL, "使用字母,数字,符号两种及以上组合,6-20个字符");
            return false;
        }
        else if(validate(value,regList.minlength6)){
            if(e.type != "keyup"){
                changeTipTxt($(this), STATE.ERROR, "长度只能在6-20字符之间");
                return false;
            }
            else{
                changeTipTxt($(this), STATE.NORMAL, "使用字母,数字,符号两种及以上组合,6-20个字符");
                return false;
            }
        }
        else{
            if(validate(value,regList.hasNumber)){
                strength++;
            }
            if(validate(value,regList.hasLetter)){
                    strength++;
            }
            if(validate(value,regList.pwdErr)){
                    strength++;
            }
        
            if(strength === 3){
                changeTipTxt($(this), STATE.NORMAL, "你的密码很安全");
            }else if(strength === 2){
                changeTipTxt($(this), STATE.NORMAL, "安全强度适中,可以用三种以上组合提高安全强度");
            }else if(strength === 1){
                changeTipTxt($(this), STATE.NORMAL, "有被盗风险,使用字母,数字,符号两种及以上组合");
            }
            if(e.type == "blur"){
                changeTipTxt($(this), STATE.SUCCESS, "");
            }
            return true;
        }
    }
    // 二次验证
    function repeatValidatePass(e){
        let value = $(this).val();
    
        if(e.type == "focus"){
            if(value.length <= 0){
                changeTipTxt($(this), STATE.NORMAL, "请再次输入密码");
                return false;
            }
        }
        if(e.type == "blur"){
            if(value.length <= 0){
                changeTipTxt($(this), STATE.HIDDEN, "");
                return false;
            }
        }
        if(value.length <= 0){
            changeTipTxt($(this), STATE.NORMAL, "请再次输入密码");
            return false;
        }
        else if(e.type == "blur"){
            if(value !== $("#pass1").val()){
                changeTipTxt($(this), STATE.ERROR, "两次密码输入不一致");
                return false;
            }
            else{
                changeTipTxt($(this), STATE.SUCCESS, "");
                return true;
            }
        }
    }
    // 验证邮箱
    function validateMail(e){
        let value = $(this).val();
        
        if(e.type == "focus"){
            if(value.length <= 0){
                changeTipTxt($(this), STATE.NORMAL, "绑定邮箱，让你体验更佳");
                return false;
            }
        }
        if(e.type == "blur"){
            if(value.length <= 0){
                changeTipTxt($(this), STATE.HIDDEN, "");
                return false;
            }
        }
        if(value.length <= 0){
            changeTipTxt($(this), STATE.NORMAL, "绑定邮箱，让你体验更佳");
            return false;
        }
        if(e.type == "blur"){
            if(validate(value, regList.mailReg)){
                changeTipTxt($(this), STATE.SUCCESS, "");
                return true;
            }
            else{
                changeTipTxt($(this), STATE.NORMAL, "格式输入错误");
                return false;
            }
        }
    }
    function validateRegister(){
        var e = {type: "blur"};
        let flag = validateUser.call($("#username")[0],e) && 
                    validatePass.call($("#pass1")[0],e) && 
                    repeatValidatePass.call($("#pass2")[0],e) && 
                    validateMail.call($("#email")[0],e);

        if(!flag || loading) return false;
        let username = $("#username").val(),
            password = $("#pass1").val(),
            email = $("#email").val();
        loading = true;

        $.ajax("http://59.110.157.147/server/group8Interface/register.php",{
            type: "POST",
            data: {
                username ,
                password,
                email,
                author: "dbp"
            }
        })
        .then(res=>{
            console.log(res);
            loading = false;
            res = JSON.parse(res);
            if(res.status === "success"){
                setTimeout( a => {
                    cookie("tocken",res.password,{
                          expires : 20,
                          path: "/"
                    });
                    cookie("username",username,{
                          expires : 20,
                          path: "/"
                    });
                    // 跳转到登录页面
                    location.href = "../login/login.html";
              },2000)
            }
            else if(res.status === "error"){
                if(res.stateCode == 4 && res.errorType == "repeat of user name")
                    changeTipTxt($("#username"),STATE.ERROR,"用户名已存在");
                else{
                    alert(res.errorType);
                }
            }
        })
    }
    function bindEvent(){
        $("#username").on("focus blur keyup",validateUser);
        $("#pass1").on("focus blur keyup",validatePass);
        $("#pass2").on("focus blur keyup",repeatValidatePass);
        $("#email").on("focus blur keyup",validateMail);
        $("#myForm").submit(function(){
            return false;
        })
        $("#reg_submit").click(validateRegister);
    }
    $(function(){
        // 购物车
        ProfileMgr.repeatLoad();
        $('.web_head').load('./header.html',function(){
            new Cart();
        });
        $('.footer').load('./footer.html');

        bindEvent();
    });
})();